package com.treasure.mall.biz.entity.user;

import com.treasure.mall.biz.base.UserDetails;
import com.treasure.mall.biz.dto.live.LiveMessageUserLevel;
import com.treasure.mall.biz.entity.BasePO;
import com.treasure.mall.biz.remote.live.TencentTools;
import com.treasure.mall.zbq.common.StringUtilsExt;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.SystemEnums;
import com.treasure.mall.zbq.common.ienum.auth.RoleEnum;
import com.treasure.mall.zbq.common.ienum.user.UserEnums;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 
 * 用户
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.entity.user
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/11 09:14
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.biz.entity.user Inc. All rights reserved.
 */
@Entity
@Getter
@Setter
@Table(name = "zb_user")
@Cacheable(false)
public class UserPO extends BasePO implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;

    @Transient
    private MerchantPO merchant;

    @Column(name = "merchant_id")
    private Long merchantId;

    @Column(name = "mobile")
    private String mobile;


    @Column(name = "real_name")
    private String realName;

    @Column(name = "nick_name")
    private String nickName;

    @Column(length = 200, name = "avatar_url")
    private String avatar;

    /**
     * 会员积分
     */
    @Column(name = "integral")
    private long integral;
    /**
     * 登录token
     */
    @Column(name = "login_token", length = 50)
    private String loginToken;

    @Column(name = "enabled")
    private Boolean enabled = true;
    /**
     * 0 默认会员新秀 1 会员达人
     * {@link com.treasure.mall.zbq.common.ienum.user.UserEnums.UserLevel}
     */
    @Column(name = "user_level")
    private UserEnums.UserLevel userLevel;

    /**
     * 0普通用户 1会员用户 {@link UserEnums.UserType}
     */
    @Column(name = "user_type")
    private UserEnums.UserType userType;

    /**
     * 上线id
     */
    @Column(name = "parent_id", length = 10)
    private Long parentId;

    @ManyToOne
    @JoinColumn(name = "wechant_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    private WechatUser wechatUser;


    @Transient
    private UserPO guider;

    /**
     * 上下线的路径
     * e.g. |1|2|3|
     */
    @Column(name = "tree_path", columnDefinition = "text")
    private String treePath;


    /**
     * 已支付开店费用
     * true1交288用户(新秀)，否则普通用户
     */
    @Column(name = "merchant_pay")
    private Boolean merchantPay = false;

    /**
     * 总余额
     */
    @Column(scale = 2, precision = 19, name = "balance")
    private BigDecimal toTalBalance = BigDecimal.ZERO;

    @Column(scale = 2, precision = 19, name = "lock_balance")
    private BigDecimal lockBalance = BigDecimal.ZERO;
    /**
     * 历史总收入
     */
    @Column(name = "history_total_amount")
    private BigDecimal historyTotalAmount = BigDecimal.ZERO;
    /**
     * 有效支付订单总金额
     */
    @Column(name = "valid_pay_order_sum")
    private BigDecimal validPayOrderSum = BigDecimal.ZERO;

    /**
     * 待入余额
     */
    @Column(scale = 2, precision = 19, name = "balance_in_Future")
    private BigDecimal balanceInFuture = BigDecimal.ZERO;

    /**
     * 专属粉丝数量
     */
    @Column(name = "advanced_buyer_team_size")
    private Integer advancedBuyerTeamSize;
    /**
     * 会员规模数量
     */
    @Column(name = "merchant_status_team_size")
    private Integer merchantStatusTeamSize;

    /**
     * 普通规模数量
     */
    @Column(name = "normal_status_team_size")
    private Integer normalStatusTeamSize;

    /**
     * 分享邀请二维码海报地址
     */
    @Column(name = "invite_qrcode", length = 200)
    private String inviteQrcode;
    /**
     * 版本号
     */
    @Column(name = "zb_version")
    private long version;

    public UserPO() {

        this.toTalBalance = BigDecimal.ZERO;
        this.balanceInFuture = BigDecimal.ZERO;
        this.historyTotalAmount = BigDecimal.ZERO;
    }

    public BigDecimal getLockBalance() {
        if (this.lockBalance == null) {
            return BigDecimal.ZERO;
        }
        return this.lockBalance;

    }

    /**
     * 最好访问时间
     */
    @Column(name = "last_visit_time", columnDefinition = Constant.DATE_COLUMN_DEFINITION)
    private LocalDateTime lastVisitTime = LocalDateTime.now();
    /**
     * 注册客户端
     */
    @Column(name = "register_client")
    private SystemEnums.Client registerClient;
    /**
     * 身份证号
     */
    @Column(name = "id_card")
    private String idCard;

    /**
     * 粉丝数量
     */
    @Column(name = "fans_count")
    private long fansCount;

    public String toIMUserName() {
        return "staging-user-" + this.userId;

    }

    public UserPO(Long userId) {
        this.userId = userId;
    }

    /**
     * 获取用户指定层级的用户ID(往上找)
     *
     * @param depth
     * @return
     */
    public Long getBelongUserId(int depth) {
        if (this.treePath == null) {
            return 0L;
        }
        String[] parents = StringUtilsExt.trim(this.treePath, '|').split("\\|");
        if (depth < parents.length) {
            return Long.valueOf(parents[parents.length - 1 - depth]);
        }
        return 0L;
    }

    /**
     * 查询所有上级用户ID（整条线）
     *
     * @return
     */
    public List<Long> getSuperiorUserIdList() {
        if (StringUtils.isEmpty(this.treePath)) {
            return new ArrayList<>();
        }
        String temp = StringUtilsExt.ltrim(StringUtilsExt.rtrim(treePath, '|'), '|');
        String[] idStrList = temp.split("\\|");
        List<Long> idList = new ArrayList<>();
        for (String idStr : idStrList) {
            if (this.userId.toString().equals(idStr)) {
                continue;
            }
            idList.add(Long.valueOf(idStr));
        }
        Collections.reverse(idList);
        return idList;
    }

    /**
     * 判断是否有上线
     *
     * @return
     */
    public boolean isExistParent() {
        return this.parentId != null && this.parentId > 0;
    }

    @Override
    public RoleEnum getRoleType() {
        return RoleEnum.USER;
    }

    @Override
    public Long getId() {
        return userId;
    }

    @Override
    public String getDisplayName() {
        return null;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return null;
    }

    @Override
    public String getUsername() {
        return mobile;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * 可用余额
     *
     * @return
     */
    public BigDecimal getBalance() {
        if (this.lockBalance == null) {
            return this.toTalBalance;
        }
        return this.toTalBalance.subtract(this.lockBalance);
    }


    public LiveMessageUserLevel getUserChatLevel() {
        return TencentTools.getMessageUserLevel(this.validPayOrderSum);
    }

}
